import {messages} from "share/common";
import React from 'react';
import { connect } from 'react-redux';
import { Select, Row, Col, message, Icon, Button, Modal, Tag, Spin } from 'antd';
import travelPolicyService from 'containers/expense-reimbursement-control/expense-standard/travel-policy/travel-policy.service';

const Option = Select.Option;

class ItineraryField extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: false,
      fieldVisible: false,
      valueList: [], //已选值列表
      optionList: [], //值列表可选范围
      selectItem: {} //当前选中项
    }
  }

  componentDidMount(){
    const { valueList } = this.props;
    this.initOptionList();
    if (valueList) {
      this.setState({valueList});
    }
  };

  componentWillReceiveProps(nextProps) {
    if (nextProps.valueList) {
      this.setState({valueList: nextProps.valueList});
    }
  };

  //初始化可选值列表范围
  initOptionList = () => {
    const { tenantMode } = this.props;
    let serviceName = tenantMode ? 'getCustomEnumerationInTenant' : 'getCustomEnumeration';
    this.setState({loading: true});
    travelPolicyService[serviceName](0, 200).then((resp) => {
      if (resp.status === 200) {
        this.setState({optionList: resp.data});
      }
    }).catch((e) => {
      if (e.response && e.response.data && e.response.data.message) {
        message.error(e.response.data.message);
      }
    }).finally(() => {
      this.setState({loading: false});
    });
  };

  showAddValue = () => {
    this.setState({fieldVisible: true});
  };

  closeAddValue = () => {
    this.setState({fieldVisible: false, selectItem: {}});
  };

  removeValue = (e, index) => {
    e.preventDefault();
    const { valueList } = this.state;
    valueList.splice(index, 1);
    this.setState({valueList});
  };

  handleSelectItem = (e, opt) => {
    let item = {
      name: opt.props['cust'].name,
      customEnumerationOID: opt.props['cust'].customEnumerationOID,
      selected: true
    };
    this.setState({selectItem: item});
  };

  handleOk = () => {
    const { valueList, selectItem } = this.state;
    const { onChange } = this.props;
    valueList.push(selectItem);
    this.setState({valueList}, () => {
      onChange(valueList);
    });
    this.closeAddValue();
  };

  //已选过的值列表要disabled，不能重复选中
  judgeDisabled = (item) => {
    const { valueList } = this.state;
    let disabled = false;
    valueList.map(value => {
      if (value.customEnumerationOID === item.customEnumerationOID) {
        disabled = true;
      }
    });
    return disabled;
  };

  render() {
    const { fieldVisible, optionList, selectItem, valueList, loading } = this.state;
    return (
      <div>
        {valueList.map((item, index) => {
          return (
            <Tag closable onClose={(e) => this.removeValue(e, index)}>
              {item.name}
            </Tag>
          )
        })}
        <Button size="small" disabled={valueList.length >= 5} onClick={this.showAddValue}>
          <Icon type="plus" />{messages('common.add'/*添加*/)}
        </Button>
        <Modal
          title={messages('expense-reimbursement-control.key86')/*值列表*/}
          visible={fieldVisible}
          onCancel={this.closeAddValue}
          maskClosable={false}
          destroyOnClose={true}
          footer={[
            <Button key="back" onClick={this.closeAddValue}>{messages('common.cancel')/*取消*/}</Button>,
            <Button key="submit" type="primary" disabled={!selectItem.customEnumerationOID} onClick={this.handleOk}>{messages('common.ok')/*确定*/}</Button>
          ]}
        >
          <Row type="flex" align="middle">
            <Col span={6} style={{textAlign: 'right'}}>
              <span style={{display: 'inline-block', marginRight: '4px', color: '#FF0000', fontFamily: 'SimSun'}}>*</span> {messages('expense-reimbursement-control.key86')/*值列表*/}：
            </Col>
            <Col offset={1} span={10}>
              <Select
                notFoundContent={!loading ? messages('components.key410'/*无匹配结果*/) : <Spin size="small"/>}
                style={{width: '100%'}}
                placeholder={messages('common.please.select')/*请选择*/}
                value={selectItem.customEnumerationOID ? selectItem.customEnumerationOID : undefined}
                onSelect={(e, opt) => this.handleSelectItem(e, opt)}
              >
                {optionList.map(item => <Option disabled={this.judgeDisabled(item)} cust={item} value={item.customEnumerationOID} key={item.customEnumerationOID}>{item.name}</Option>)}
              </Select>
            </Col>
          </Row>
        </Modal>
      </div>
    )
  }
}

function mapStateToProps(state) {
  return {
    tenantMode: state.main.tenantMode
  }
}

ItineraryField.propTypes = {
  valueList: React.PropTypes.array,
  onChange: React.PropTypes.func  //更改属性时的回调
};

ItineraryField.defaultProps = {
  valueList: []
};

export default connect(mapStateToProps)(ItineraryField);
